<template>
  <div class="switch-body">
    <template v-if="inPage=='preview' || inPage=='dataBoard'">
      <div class="switch-body-list" v-for="(item, index) in tableList">
        <p class="switch-body-p">{{ nowValue }}</p>
        <el-switch
          v-model="item.data"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="changeLine(index)">
        </el-switch>
        <p class="switch-body-p">{{ (item.name || item.sku) || '开关' }}</p>
      </div>
    </template>
    <template v-else>
      <div class="switch-body-list">
        <p class="switch-body-p">{{ nowValue }}</p>
        <el-switch
          v-model="switchValue"
          active-color="#13ce66"
          inactive-color="#ff4949">
        </el-switch>
        <p class="switch-body-p">{{ titleName }}</p>
      </div>
    </template>
  </div>
</template>

<script>
import {deviceCommandDown} from '@/api/system/board'
import {devicecommandlist} from "@/api/system/command"
import {paneldetailData} from "@/api/system/board"

export default {
  props: ['keyData', 'inPage', 'boardData', 'componentsId'],
  name: "board4",
  data() {
    return {
      switchValue: true,
      nowValue: 'ON',
      titleName: 'switch',
      tableList: []
    }
  },
  mounted() {
    if (this.inPage === 'dataBoard') {
      paneldetailData({id: this.componentsId}).then(res => {
        this.tableList = res.data
      })
    }
  },
  watch: {
    switchValue() {
      console.log('boardData:', this.boardData)
      console.log('switchValue', this.switchValue, this.keyData)
    }
  },
  methods: {
    changeLine(index) {
      devicecommandlist({deviceId: this.tableList[index].id}).then(res => {

        for (let item of res.rows) {
          if (item.sku === this.tableList[index].sku && item.value === this.tableList[index].data.toString()) {
            this.downRule(this.tableList[index].id, item.command)
          }
        }
      })
    },
    downRule(id, command) {
      let new_ = JSON.parse(command)
      let new_l = []
      for(let item of new_){
        new_l.push(JSON.stringify(item))
      }
      let data_ = {
        id: Number(id), //  设备id
        command: new_l, // 数组
      }
      deviceCommandDown(data_).then(res=>{
        console.log('指令:', res)
      })
    }
  }
}
</script>

<style scoped>
.switch-body {
  width: 100%;
  height: 100%;
  display: flex;
}

.switch-body-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.switch-body-p {
  padding: 5px 0;
  margin: 0;
  font-size: 14px;
}
</style>
